<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class SysConfig extends Model
{
    protected $primaryKey = 'key';

    protected $keyType = 'varchar';

    protected $table = 'sys_config';

    public $timestamps = false;

    public static function loadAll()
    {
        $result = [];
        $rows = static::all();
        foreach ($rows as $row) {
            if ($row->type == 'int') {
                $result[$row->key] = (int)$row->value;
            } elseif ($row->type == 'bool') {
                $result[$row->key] = $row->value == 'true';
            } else {
                $result[$row->key] = $row->value;
            }
        }
        return $result;
    }

    /**
     * @param $key
     * @return bool|int|string|null
     */
    public static function loadValueByKey($key) {
        $row = static::find($key);
        if ($row === null) {
            return null;
        }
        $type = $row->type;
        $value = $row->value;
        return $type == 'int' ? (int)$value : ($type == 'bool' ? $value == 'true' : $value);
    }

}
